import { Component, OnInit } from '@angular/core';
import { Route, Router, ActivatedRoute, Params } from '@angular/router';
import 'rxjs/add/operator/switchMap';
import { ChannelManageService } from '../../../shared/services/channel.service';
import { DictService } from '../../../shared/services/dict.service';
import * as moment from 'moment';
import { RecipesManageService } from '../../../shared/services/recipes.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { LabelManageService } from '../../../shared/services/label.service';
import { LoginService } from '../../../shared/services/login.service';


@Component({
  selector: 'app-recipes-manage',
  templateUrl: './recipes-manage.component.html',
  styleUrls: ['./recipes-manage.component.scss']
})

export class RecipesManageComponent implements OnInit {

  _value = '';

  _allChecked = false;
  _indeterminate = false;
  _displayData = [];
  _loading = false;
  data = [];

  options = [];
  selectedOption;

  selectedLabel;
  labelOptions = [];

  selectedFlow;
  flowOptions = [];

  selectedGrounding;
  groundingOptions = [];
  expandDataCache = {};

  _dateRange = [null, null];

  recipesParams: any;

  shi: any;

  constructor(
    private route: ActivatedRoute,
    private dictService: DictService,
    private _message: NzMessageService,
    private _modal: NzModalService,
    private loginService: LoginService,
    private labelManageService: LabelManageService,
    private recipesManageService: RecipesManageService,
    private channelManageService: ChannelManageService,
    private router: Router
  ) {}

  ngOnInit() {
    const that = this;
    this.reset();
    // 获取渠道树
    this.channelManageService.getChannelTree().map(res => {
      const arr = res['data'];
      arr.unshift({id: '', name: '全部渠道'});
      return arr;
    }).subscribe(res => {
      // console.log(res);
      if (res) {
        this.options = res;
        const timer = setTimeout(() => {
          this.selectedOption = [
            {id: '全部渠道', name: '全部渠道', selected: true}
          ];
          clearInterval(timer);
        });
      }
    });
    // const timer = setTimeout(() => {
    //   this.selectedOption = [
    //     {id: '全部渠道', name: '全部渠道', selected: true}
    //   ];
    //   // getIndex = 0;
    //   clearInterval(timer);
    // }, 10);
    // 判断列表页有没有带参数返回的
    // const timerDD = setTimeout(() => {
      that.route.queryParams.subscribe(params => {
        // console.log(params);
        if (params['searchCriteria']) {
          const timerd = setTimeout(() => {

            that.recipesParams = JSON.parse(params['searchCriteria']);
            // console.log(that.recipesParams);
            // 渠道对等
            // console.log(this.options);
            const searchArr = JSON.parse(JSON.stringify(that.options));
            const searchPar = JSON.parse(JSON.stringify(that.recipesParams.channelArray));
            const channelParam = [];
            if (searchPar.length > 0) {
              const getChannel = function(arr_i, arr) {
                // console.log(searchPar)
                if (searchPar.length > 0) {
                  if (arr_i === searchPar.length) {
                    // over
                  } else {
                    arr.forEach(item => {
                      if (item['id'] === searchPar[arr_i]) {
                        // console.log(item);
                        channelParam.push(item);
                        arr_i++;
                        getChannel(arr_i, item.children);
                      }
                    });
                  }
                }
              };
              getChannel(0, searchArr);
              // console.log(channelParam);
              that.selectedOption = channelParam;
            } else {
              that.selectedOption = [{id: '全部渠道', name: '全部渠道', selected: true}];
            }
            that.getRecipesData();
          }, 300);
        }
      });
      // clearInterval(timerDD);
    // }, 20);

    // 获取流程状态
    this.flowOptions = this.dictService.FlowStatus;
    if (!this.flowOptions.find(i => i['key'] === '全部流程')) {
      this.flowOptions.unshift({key: '全部流程', value: ''});
    }
    // 获取上架状态
    this.groundingOptions = this.dictService.PubStatus;
    if (!this.groundingOptions.find(i => i['key'] === '全部状态')) {
      this.groundingOptions.unshift({key: '全部状态', value: ''});
    }
    // 获取全部标签
    this.labelManageService.getAllLabelList().subscribe(res => {
      this.labelOptions = res['data'];
      if (!this.labelOptions.find(i => i['name'] === '全部标签')) {
        this.labelOptions.unshift({name: '全部标签', id: ''});
      }
      this.selectedLabel = this.labelOptions[0];
    });
    // 默认搜索
    // this.getRecipesData();
    // 市场部修改为 recipes/list/110
    this.shi = this.loginService.user.authList.find(i => i === 'recipes/list/110') ? true : false;
  }

  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  }
  _startValueChange = () => {
    if (this.recipesParams.startDate > this.recipesParams.endDate) {
      this.recipesParams.endDate = null;
    } else {
      if (!this.recipesParams.startDate) {
        this.recipesParams.startDate = '';
      }
      // 搜索
      this.getRecipesData('update');
    }
  }
  _endValueChange = () => {
    if (this.recipesParams.startDate > this.recipesParams.endDate) {
      this.recipesParams.startDate = null;
    } else {
      // console.log(this.recipesParams.endDate);
      if (this.recipesParams.endDate === null) {
        this.recipesParams.endDate = '';
      }
      // 搜索
      this.getRecipesData('update');
    }
  }
  // _disabledStartDate = (startValue) => {
  //   if (!startValue || !this.recipesParams.endDate) {
  //     return false;
  //   }
  //   return startValue.getTime() >= this.recipesParams.endDate.getTime();
  // }
  // _disabledEndDate = (endValue) => {
  //   if (!endValue || !this.recipesParams.startDate) {
  //     return false;
  //   }
  //   return endValue.getTime() <= this.recipesParams.startDate.getTime();
  // }
  get _isSameDay() {
    return this.recipesParams.startDate && this.recipesParams.endDate && moment(this.recipesParams.startDate).isSame(this.recipesParams.endDate, 'day')
  }
  get _endTime() {
    return {
      nzHideDisabledOptions: true,
      nzDisabledHours: () => {
        return this._isSameDay ? this.newArray(this.recipesParams.startDate.getHours()) : [];
      },
      nzDisabledMinutes: (h) => {
        if (this._isSameDay && h === this.recipesParams.startDate.getHours()) {
          return this.newArray(this.recipesParams.startDate.getMinutes());
        }
        return [];
      },
      nzDisabledSeconds: (h, m) => {
        if (this._isSameDay && h === this.recipesParams.startDate.getHours() && m === this.recipesParams.startDate.getMinutes()) {
          return this.newArray(this.recipesParams.startDate.getSeconds());
        }
        return [];
      }
    }
  }

  // 更改渠道id
  channelChange($event) {
    // console.log($event);
    if ($event) {
      this.recipesParams.channelArray = JSON.parse(JSON.stringify($event));  // 用于返回回参
      const obj = $event.pop();
      this.recipesParams.channelId = obj;
      // 搜索
      this.getRecipesData();
    }
  }

  // 更改时间选择
  dateSelectChange(event) {
    // console.log(event);
    if (event) {
      // 搜索
      this.getRecipesData();
    }
  }

  onSearch(event: string): void {
    // console.log(event);
    this.recipesParams.name = event;
    this.getRecipesData('update');
  }

  // 重置所有搜索参数
  update() {
    // 获取流程状态
    this.reset();
    this.selectedOption = [{id: '全部渠道', name: '全部渠道'}];
    this.getRecipesData('update');
  }

  _displayDataChange($event) {
    this._displayData = $event;
    this._refreshStatus();
  }

  _refreshStatus() {
    const allChecked = this.data.every(value => value['checked'] === true);
    const allUnChecked = this.data.every(value => !value['checked']);
    this._allChecked = allChecked;
    this._indeterminate = !allChecked && !allUnChecked;
  }

  _checkAll(value) {
    if (value) {
      this.data.forEach(item => {
        item['checked'] = true;
      });
    } else {
      this.data.forEach(item => {
        item['checked'] = false;
      });
    }
    this._refreshStatus();
  }

  _console(value) {
    // console.log(value);
  }

  locationRecipesDetail() {
    this.router.navigate(['./detail'], {
      relativeTo: this.route,
      queryParams: {
        type: 'create',
        searchCriteria: JSON.stringify(this.recipesParams)
      }
    });
  }

  // 获取list数据
  getRecipesData(type: String = 'create') {
    this.recipesParams.startDate = moment(this.recipesParams['startDate']).format('YYYY/MM/DD');
    this.recipesParams.endDate = moment(this.recipesParams['endDate']).format('YYYY/MM/DD');
    // console.log(this.recipesParams);
    this._loading = true;
    this.recipesManageService.getRecipesList(this.recipesParams)
        .subscribe(res => {
          // console.log('食谱列表: ', res);
          if (res['code'] === '0') {
            this.recipesParams.pageNumber = res['data']['pageNumber'];
            this.recipesParams.totalPages = res['data']['totalPages'] * this.recipesParams.pageSize;
            this.data = res['data']['list'];
            if (type === 'update') {
              this._message.success('数据已更新', {nzDuration: 2000});
            }
            if (this._loading) {
              this._loading = false;
            }
          }
        });
  }

  reset() {
    this.recipesParams = {
      name: '',       // 食谱名称，模糊查询
      tagId: '',      // 标签id
      flowStatus: '',   // 流程状态：
                          // 待产品部完善
                          // 待运营部完善
                          // 待市场部完善
                          // 完成
      pubStatus: '',    // 上下架状态:
                          // 未上架
                          // 上架
      startDate: '2018/01/01', // moment().subtract(180, 'days').format('YYYY/MM/DD'),  // 创建日期开始
      endDate: moment(new Date()).format('YYYY/MM/DD'),    // 创建日期结束
      dateSelect: [moment().subtract(30, 'days').format('YYYY/MM/DD'), moment(new Date()).format('YYYY/MM/DD')], // 时间选择 model
      channelId: '',  // 渠道id
      channelArray: [], // 当前渠道数组
      pageSize: 10,   // 分页参数，每页多少条记录，不传参默认为20
      pageNumber: 1,  // 分页参数,请求第几页,不传参默认为1
    };
  }

  // 编辑
  hrefRecipesEdit(item) {
    this.router.navigate(['./detail'], {
      relativeTo: this.route,
      queryParams: {
        type: 'edit',
        id: item['id'],
        searchCriteria: JSON.stringify(this.recipesParams)
      }
    });
  }

  // 查看
  hrefRecipesSee(item) {
    this.router.navigate(['./detail'], {
      relativeTo: this.route,
      queryParams: {
        type: 'see',
        active: 'see',
        id: item['id'],
        searchCriteria: JSON.stringify(this.recipesParams)
      }
    });
  }

  // 修改图文
  hrefRecipesIMGActiveEdit(item) {
    this.router.navigate(['./detail'], {
      relativeTo: this.route,
      queryParams: {
        type: 'see',
        active: 'edit',
        id: item['id'],
        searchCriteria: JSON.stringify(this.recipesParams)
      }
    });
  }

  // 修改上下架
  hrefRecipesGroundingEdit(item) {
    this.router.navigate(['./detail'], {
      relativeTo: this.route,
      queryParams: {
        type: 'see',
        grounding: 'edit',
        id: item['id'],
        searchCriteria: JSON.stringify(this.recipesParams)
      }
    });
  }

  // 分页搜索
  pageChange(reset = false) {
    if (reset) {
      this._allChecked = false;
      this._indeterminate = false;
      this.getRecipesData('update');
    }
  }

  delete(item) {
    // console.log(item);
    const that = this;
    const params = {
      idsName: '',
      ids: [],
    };
    if (!item) {
      // 删除全部
      params.ids = this.data.reduce((pre, next) => {
        if (next['checked']) {
          params.idsName += next['name'] + ' ,';
          pre.push(next.id);
        }
        return pre;
      }, []);
    } else {
      // 删除单个
      params.idsName = item['name'];
      params.ids.push(item['id']);
    }
    // console.log(params.ids);
    if (params.ids.length < 1) {
      return false;
    }
    this._modal.confirm({
      title  : '您是否确认要删除这些食谱?',
      content: `<b>食谱： ${params.idsName}</b>`,
      onOk() {
        // console.log('确定');
        that.recipesManageService.postDeleteChannel(params)
            .subscribe(res => {
              // console.log(res);
              if (res['msg'] === '成功') {
                that._message.success('食谱删除成功', {nzDuration: 2000});
                that._indeterminate = false;
                that.reset();
                that.getRecipesData('update');
              }
            });
      },
      onCancel() {
        // console.log('取消');
      }
    });
  }

}
